//
//  oAuthController.swift
//  MyWeibo
//
//  Created by tanchao on 15/7/31.
//  Copyright © 2015年 chaoren. All rights reserved.
//

import UIKit
import SVProgressHUD
class oAuthController: UIViewController,UIWebViewDelegate {

//    MARK:- 加载webView
    override func loadView() {
        view = webView;
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
//    关闭
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.delegate = self
        webView.loadRequest(NSURLRequest(URL: WeiboNetWorkingTools.sharedNetWorkingTools.oathUrl()))
    }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlStr = request.URL!.absoluteString
        if !urlStr.hasPrefix(WeiboNetWorkingTools.sharedNetWorkingTools.redirectUri){
            return true
        }
        if let query = request.URL?.query where query.hasPrefix("code="){
           let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            loadAccesstoken(code)
        }else{
            close()
        }
        return false
    }
    
//    MARK:- 获取token
    private func loadAccesstoken(code:String){
        WeiboNetWorkingTools.sharedNetWorkingTools.loadAccesstoken(CODE: code) { (result, error) -> () in
            if error != nil || result == nil{
                self.netError()
                return
            }
            UserAccount(dict: result!).loadUserInfo({ (error) -> () in
                if error != nil{
                    self.netError()
                    return
                }
//                // 发送通知切换视图控制器
                NSNotificationCenter.defaultCenter().postNotificationName(WeiboRootViewControllerSwitchNotification, object: false)
                // 关闭控制器（单独讲）Modal 出来的控制器，一定注意需要 dismiss!
                self.close()
            })
        }
    }
    // 出错处理
    private func netError(){
        SVProgressHUD.showInfoWithStatus("您的网速不给力")
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC ))
        dispatch_after(when, dispatch_get_main_queue()){
            self.close()
        }
    }
    // 懒加载webView
    lazy private  var webView: UIWebView = {
        let object = UIWebView()
        //    设置object其他属性 ...
        return object
        }()
}
